# -*- coding: utf-8 -*-

import pymysql
import pymysql.cursors

from src.sshconn.ssh_conn import singleton


@singleton
class MysqlReadPipeline(object):
    """
    同步读mysql
    """

    def __init__(self):
        self.conn = pymysql.connect(host="127.0.0.1", user="root",
                                    password="12345678", db="local_db",
                                    charset="utf8", use_unicode=True, port=3306)
        self.cursor = self.conn.cursor()

    def process_item(self, item):
        """
        对外提供调用方法
        """
        # offset count
        query_sql = """
                    select * from ucloud_t where download_state = %s ORDER BY id LIMIT %s, %s
                """
        args = (item.get("download_state", 2), item.get("offset", 0), item.get("count", 0))
        self.cursor.execute(query_sql, args)
        results = self.cursor.fetchall()
        log_list = []
        for row in results:
            dic = {'id': row[0], 'BucketName': row[1], 'FileName': row[2], 'Hash': row[3],
                   'MimeType': row[4], 'first_object': row[5], 'Size': row[6], 'CreateTime': row[7],
                   'ModifyTime': row[8], 'download_state': row[9], 'local_file_path': row[10]}
            log_list.append(dic)
        return log_list


def read_list(item):
    return MysqlReadPipeline().process_item(item)

